import './App.css';
import { Routes, Route, useLocation, useNavigate } from "react-router-dom"
import Login from './pages/login'
import Register from './pages/register'
import Epic from './pages/epic'
import Layout from './pages/components/layout'
import Project from './pages/project'
import { notification } from 'antd';
import EventBus from './util/event'
import { lazy, Suspense, useEffect } from 'react';
import { getOrgsAsync, getTaskTypesAsync, getUsersAsync } from './redux/slice/project';
import { useDispatch } from 'react-redux';


const AsyncKanbanPage = lazy(() => import(/* webpackChunkName: "kanban_page" */'./pages/kanban'))
function KanbanPage () {
    return (
        <Suspense fallback={<div>Loading...</div>}>
            <AsyncKanbanPage />
        </Suspense>
    )
}

function App() {
  const location = useLocation()
  const navigate = useNavigate()
  const dispatch = useDispatch()

  // 全局通知
  const [api, contextHolder] = notification.useNotification();
  const openNotification = (msg, type) => {
      api[`${type}`]({
          message: msg,
          placement: 'topRight',
          duration: 3
      });
  };
  

  useEffect(() => {
      if(location.pathname === '/') {
          navigate('/project')
      }

      // 页面初始获取数据：
      dispatch(getUsersAsync())
      dispatch(getOrgsAsync())
      dispatch(getTaskTypesAsync())

      // 全局监听信息：
      EventBus.on("global_not_login", function (msg) {
        navigate('/login')
      })
      EventBus.on("global_error_tips", function (msg) {
        openNotification(msg, 'error')
      })
      EventBus.on("global_success_tips", function (msg) {
        openNotification(msg, 'success')
      })
  }, [])

  return ( 
      <div className="App">
          {contextHolder}
          <Routes>
              <Route element={<Layout />}>
                  <Route path='/project/:id/kanban' element={<KanbanPage />}></Route>
                  <Route path='/project/:id/epic' element={<Epic />}></Route>
                  <Route path='/project' element={<Project />}></Route>
              </Route>
              <Route path='/login' element={<Login />} />
              <Route path='/register' element={<Register />} />
          </Routes>
      </div>
  );
}

export default App;
